package org.devops
def SonarQubeAnalysis(String projectName, String sonarServer, String credentialsId) {
    def sonarqubeScanner = tool name: 'SonarScanner501'
    // 使用 SonarQube 环境
    withSonarQubeEnv(sonarServer) {
        // 使用 Jenkins 凭据中的 SonarQube 令牌
        withCredentials([string(credentialsId: credentialsId, variable: 'SONAR_TOKEN')]) {
            // 执行 SonarQube Scanner CLI 分析
            sh """
            ${sonarqubeScanner}/bin/sonar-scanner \
                -Dsonar.projectKey=${projectName} \
                -Dsonar.projectName=${projectName} \
                -Dsonar.sources=src \
                -Dsonar.java.binaries=target/classes \
                -Dsonar.host.url=${env.SONAR_HOST_URL} \
                -Dsonar.login=${env.SONAR_AUTH_TOKEN}
            """
        }
    }
}

def checkQualityGate(int timeoutMinutes) {
    timeout(time: timeoutMinutes, unit: 'MINUTES') {
        script {
            def qg = waitForQualityGate() // 等待 SonarQube 的质量门结果
            if (qg.status != 'OK') { // 检查质量门的状态
                error "Pipeline aborted due to quality gate failure: ${qg.status}" // 中止流水线
            }
        }
    }
}

def waitForSonarQubeAnalysis(String sonarServer, String credentialsId, String projectName, int timeoutMinutes) {
    //echo "Project Name: ${projectName}"
    withSonarQubeEnv(sonarServer) {
        withCredentials([string(credentialsId: credentialsId, variable: 'SONAR_AUTH_TOKEN')]) {
            timeout(time: timeoutMinutes, unit: 'MINUTES') {
                waitUntil {
                    def curlCommand = "curl -s -u \$SONAR_AUTH_TOKEN: \$SONAR_HOST_URL/api/project_analyses/search?project=${projectName}"
                    def response = sh(script: curlCommand, returnStdout: true).trim()
                    def exitCode = sh(script: curlCommand, returnStatus: true)

                    echo "Response from SonarQube: ${response}"

                    if (exitCode != 0) {
                        error("Curl command failed with exit code: ${exitCode}. Response: ${response}")
                    }

                    if (response) {
                        try {
                            def jsonResponse = readJSON(text: response)
                            if (jsonResponse.analyses && jsonResponse.analyses.size() > 0) {
                                def latestAnalysis = jsonResponse.analyses[0]
                                echo "Latest Analysis Key: ${latestAnalysis.key}, Date: ${latestAnalysis.date}"

                                if (latestAnalysis.events.size() > 0) {
                                    echo "New events found in analysis."
                                } else {
                                    echo "No new events found in analysis."
                                }

                                return true
                            } else {
                                error("No analyses found in the response.")
                            }
                        } catch (Exception e) {
                            error("Failed to parse JSON response: ${e.message}. Response: ${response}")
                        }
                    } else {
                        error("Received empty response from SonarQube.")
                    }
                }
            }
        }
    }
}
